package v1

import (
	"github.com/Unknwon/com"
	"github.com/gin-gonic/gin"
	"middleware/validation"
	"pkg/app"
	"pkg/e"
	"pkg/export"
	"pkg/logging"
	"pkg/setting"
	"pkg/upload"
	"service/auth_service"
	"util"
)

// 账号列表
func GetAuths(c *gin.Context) {
	appG := app.Gin{C: c}
	// 入参
	authService := auth_service.Auth{
		PageNum:  util.GetPage(c),
		PageSize: setting.AppSetting.PageSize,
	}

	// 统计
	total, err := authService.Count()
	if err != nil {
		appG.Response500(e.ERROR_COUNT_AUTH_FAIL, nil)
		return
	}

	// 获取数据
	auths, err := authService.GetAll()
	if err != nil {
		appG.Response500(e.ERROR_GET_AUTHS_FAIL, nil)
		return
	}

	// 封装数据
	data := make(map[string]interface{})
	data[e.List] = auths
	data[e.Total] = total

	appG.Response200(data)
}

// 当前登录账号
func GetCurrentAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	token := c.Query("token")
	if token == "" {
		token = c.GetHeader("token")
	}

	// 当前登录账号
	claims, err := util.GetCurrentAuth(c)
	if err != nil {
		appG.Response500(e.ERROR_GET_TOKEN_FAILT, nil)
		return
	}

	appG.Response200(claims)
}

type AddAuthForm struct {
	Username string `form:"username" valid:"Required;MaxSize(50)"`
	Password string `form:"password" valid:"Required;MaxSize(50)"`
	Mobile   string `from:"mobile" valid:"Required;Phone"`
}

// 新增账号
func AddAuth(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
		form AddAuthForm
	)
	httpCode, errCode, msg := app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.Response(httpCode, errCode, msg)
		return
	}

	// 入参
	authService := auth_service.Auth{
		Username: form.Username,
		Password: form.Password,
		Mobile:   form.Mobile,
	}

	// 新增返回自增id
	id, err := authService.Add()
	if err != nil {
		appG.Response500(e.ERROR_ADD_AUTH_FAIL, nil)
		return
	}
	appG.Response200(id)
}

// 根据id查询账号
func GetAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	id := com.StrTo(c.Param("id")).MustInt()
	valid := validation.Validation{}
	valid.Min(id, 1, "id")
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response400(valid.Errors)
		return
	}

	// 入参
	authService := auth_service.Auth{
		ID: id,
	}

	// 验证id是否存在
	exists, err := authService.ExistAuthByID()
	if err != nil {
		appG.Response500(e.ERROR_CHECK_EXIST_AUTH_FAIL, nil)
		return
	}
	if !exists {
		appG.Response200code(e.ERROR_NOT_EXIST_AUTH, nil)
		return
	}

	// 取账号
	auth, err := authService.Get()
	if err != nil {
		appG.Response500(e.ERROR_GET_AUTH_FAIL, nil)
		return
	}

	appG.Response200(auth)
}

type EditAuthForm struct {
	ID       int    `form:"id" valid:"Required"`
	Password string `form:"password" valid:"Required;MaxSize(50)"`
	Mobile   string `from:"mobile" valid:"Required;Phone"`
}

// 修改
func EditAuth(c *gin.Context) {
	// 入参
	var (
		appG = app.Gin{C: c}
		form EditAuthForm
	)
	httpCode, errCode, msg := app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.Response(httpCode, errCode, msg)
		return
	}

	// 当前登录账号id
	currentId, err := util.GetCurrentAuthID(c)
	if err != nil {
		appG.Response500(e.ERROR_GET_TOKEN_FAILT, nil)
		return
	}

	authService := auth_service.Auth{
		ID:         form.ID,
		Password:   form.Password,
		Mobile:     form.Mobile,
		ModifiedBy: currentId,
	}

	// id 是否存在
	exists, err := authService.ExistAuthByID()
	if err != nil {
		appG.Response500(e.ERROR_CHECK_EXIST_AUTH_FAIL, nil)
		return
	}
	if !exists {
		appG.Response200code(e.ERROR_NOT_EXIST_AUTH, nil)
		return
	}

	// 修改
	err = authService.Edit()
	if err != nil {
		appG.Response500(e.ERROR_EDIT_AUTH_FAIL, nil)
		return
	}

	appG.Response200(nil)
}

// 删除
func DeleteAuth(c *gin.Context) {
	appG := app.Gin{C: c}

	// 入参
	valid := validation.Validation{}
	id := com.StrTo(c.Param("id")).MustInt()
	valid.Min(id, 1, "id").Message("ID必须大于0")
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response200code(e.INVALID_PARAMS, valid.Errors)
		return
	}

	authService := auth_service.Auth{
		ID: id,
	}

	// id 是否存在
	exists, err := authService.ExistAuthByID()
	if err != nil {
		appG.Response500(e.ERROR_CHECK_EXIST_AUTH_FAIL, nil)
		return
	}
	if !exists {
		appG.Response200code(e.ERROR_NOT_EXIST_AUTH, nil)
		return
	}

	// 删除
	err = authService.Delete()
	if err != nil {
		appG.Response500(e.ERROR_DELETE_AUTH_FAIL, nil)
		return
	}

	appG.Response200(nil)
}

// 导出
func ExportAuth(c *gin.Context) {
	appG := app.Gin{C: c}

	// 创建目录
	fullPath := export.GetExcelFullPath()
	err := util.CheckFullPath(fullPath)
	if err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR_UPLOAD_CHECK_EXPORT_FAIL, nil)
		return
	}

	// 创建excel
	authService := auth_service.Auth{}
	filename, err := authService.Export()
	if err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR_EXPORT_AUTH_FAIL, nil)
		return
	}

	// 返回下载路径
	appG.Response200(map[string]string{
		e.Export_url:      export.GetExcelFullUrl(filename),
		e.Export_save_url: export.GetExcelPath() + filename,
	})
}

// 导入
func ImportAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	file, excel, err := c.Request.FormFile("file")

	// 不是excel文件
	if !upload.CheckExcelExt(excel.Filename) {
		appG.Response400code(e.ERROR_UPLOAD_CHECK_EXCEL_FAIL, nil)
		return
	}

	if err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR, nil)
		return
	}

	// 导入
	authService := auth_service.Auth{}
	err = authService.Import(file)
	if err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR_IMPORT_AUTH_FAIL, nil)
		return
	}

	appG.Response200(nil)

}
